package com.leo.erp.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leo.erp.dao.AccountHeadDao;
import com.leo.erp.dto.AccountHeadExecution;
import com.leo.erp.service.AccountHeadService;
import com.leo.erp.util.GlobalRuntimeException;

@Service
public class AccountHeadServiceImpl implements AccountHeadService{
	@Autowired
	private AccountHeadDao accountHeadDao;

	@Override
	public AccountHeadExecution findTotalPay(int supplierId, String endTime, String supType) {
		AccountHeadExecution ae = new AccountHeadExecution();
		Double sum = 0.0;
		int i = 1;
        if (("customer").equals(supType)) { //客户
            i = 1;
        } else if (("vendor").equals(supType)) { //供应商
            i = -1;
        }
        //收付款部分
        sum = sum + ((allMoney(supplierId, "付款", "合计",endTime) + allMoney(supplierId, "付款", "实际",endTime)) * (i));
        sum = sum - ((allMoney(supplierId, "收款", "合计",endTime) + allMoney(supplierId, "收款", "实际",endTime)) * (i));
        sum = sum + ((allMoney(supplierId, "收入", "合计",endTime) - allMoney(supplierId, "收入", "实际",endTime)) * (i));
        sum = sum - ((allMoney(supplierId, "支出", "合计",endTime) - allMoney(supplierId, "支出", "实际",endTime)) * (i));
		
        ae.setTotalPay(sum);
        
		return ae;
	}

	/**
	 * 统计总金额
	 * @param supplierId
	 * @param string
	 * @param string2
	 * @param endTime
	 * @return
	 */
	private Double allMoney(int supplierId, String type, String mode, String endTime) {
		Double allMoney = null;
		try {
			Double sum = findAllMoney(supplierId, type, mode, endTime);
			if(sum != null) {
                allMoney = sum;
            }
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		if(allMoney == null) {
			allMoney = 0.0;
		}
		//返回正数，如果负数也转为正数
		allMoney = Math.abs(allMoney);
		return allMoney;
	}

	private Double findAllMoney(int supplierId, String type, String mode, String endTime) {
		String modeName = "";
        if (mode.equals("实际")) {
            modeName = "ChangeAmount";
        } else if (mode.equals("合计")) {
            modeName = "TotalPrice";
        }
        Double result = null;
        try {
			result = accountHeadDao.findAllMoney(supplierId, type, modeName, endTime);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
        if(result == null) {
        	result = 0.0;
        }
		return result;
	}
	
	
}
